<template>
  <div class="app-container charts">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="60px">
                        <el-form-item label="基准" prop="factoryId" label-width="40px">
                          <el-radio-group v-model="queryParams.radio" @change="radioChangeVal">
                            <el-radio label="EQP"> EQP </el-radio>
                            <el-radio label="UNIT"> Unit </el-radio>
                          </el-radio-group>
                        </el-form-item>
                        <el-form-item label="制造区域" prop="factoryAreaId">
                            <el-select v-model="queryParams.factoryAreaId" placeholder="区域" clearable @change="areaChange" style="width: 70px">
                                <el-option
                                        v-for="dict in factoryAreaIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="制造类型" prop="productionTypeId">
                            <el-select v-model="queryParams.productionTypeId" placeholder="制造类型" clearable @change="productionTypeIdChange" style="width: 80px">
                                <el-option
                                        v-for="dict in listProductionTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="设备类型" prop="machineTypeId">
                            <el-select v-model="queryParams.machineTypeId" placeholder="设备类型" clearable @change="machineTypeIdChange" style="width: 90px">
                                <el-option
                                        v-for="dict in listMachineTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="EOP_ID" prop="eqpType">
                              <el-select v-model="queryParams.eqpType" placeholder="EOP_ID" clearable @change="eqpTypeChange" style="width: 120px">
                                <el-option
                                        v-for="dict in listEqpTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                            <el-button style="margin-left: 10px;" type="primary" icon="Search" @click="getChartData" v-if="queryParams.radio !== 'UNIT'">查询</el-button>
                            <el-button type="warning" plain icon="Download" @click="handleExport" v-if="queryParams.radio !== 'UNIT'">导出</el-button>
                          </el-form-item>

                          <el-form-item label="UNIT" prop="eqpType" v-if="queryParams.radio === 'UNIT'" label-width="40px">
                            <el-select v-model="queryParams.unitType" placeholder="UNIT类型" clearable style="width: 130px">
                                <el-option
                                        v-for="dict in listUnitTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                            <el-button style="margin-left: 10px;" type="primary" @click="getChartData">查询</el-button>
                            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                          </el-form-item>

    </el-form>
    <el-button type="success" plain @click="getDetails" style="margin-top: -37px; float: right;">※ 图例</el-button>

    <el-dialog v-model="open" width="500px" title="K线图图例说明" append-to-body>
      <img src="@/assets/images/candlestickChart.png" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>

    <div id="chart" style="width: 100%; height: calc(100% - 40px);"></div>
  </div>
</template>

<script setup name="AstOneDay">
  import { factoryAreaIdOptions, listProductionTypeOptions, listMachineTypeOptions } from '@/common/options'
  import { getMachineTypeId, getModelType, getEqpTypeId } from '@/common/affect'

  import { getEqpChartData, getUnitOptions } from '@/api/indexAnalyse/astOneDay'
  import moment from 'moment'
  import * as echarts from 'echarts'

  const { proxy } = getCurrentInstance()

  // 基于准备好的dom，初始化echarts实例
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    factoryId: null,
    factoryAreaId: null,
    productionTypeId: null,
    machineTypeId: null,
    machineId: null,
    eqpType: null,
    unitType: null,
    radio: 'EQP'
  })

  const listEqpTypeOptions = ref([])
  const listUnitTypeOptions = ref([])

  const open = ref(false)

  const splitData = (rawData) => {
    let categoryData = []
    let values = []
    let volumes = []
    let average = []
    let mode = []
    let tenDayAst = []
    let oneDayeCv = []
    let tenDayeCv = []
    let ast = []
    let productId = []
    for (let i = 0; i < rawData.length; i++) {
      categoryData.push(rawData[i].dataTime.slice(2).replaceAll('-', '/')) /* 时间格式化 */
      // values.push([rawData[i].eQ1, rawData[i].eQ2, rawData[i].eMin, rawData[i].eQ3])
      /**
       * 与ST目标值相对比
       * 大于的 colourFlag = 1 红色
       * 开盘价 > 收盘价
       *
      */

      if(rawData[i].eQ1 === rawData[i].eQ2){
        rawData[i].eQ2 = rawData[i].eQ2 + 0.001
      }
      if(rawData[i].colourFlag){
        values.push([rawData[i].eQ1, rawData[i].eQ2, rawData[i].eMin, rawData[i].eQ3])
      } else {
        values.push([rawData[i].eQ2, rawData[i].eQ1, rawData[i].eMin, rawData[i].eQ3])
      }
      volumes.push([i, rawData[i].sampleCount, 1])
      average.push(rawData[i].eAverage)
      mode.push(rawData[i].eMode)
      tenDayAst.push(rawData[i].tenDayAst)
      oneDayeCv.push(rawData[i].oneDayeCv)
      tenDayeCv.push(rawData[i].tenDayeCv)
      ast.push(rawData[i].ast)
      productId.push(rawData[i].productId)
    }
    return {
      categoryData: categoryData,
      values: values,
      volumes: volumes,
      average: average,
      mode: mode,
      oneDayeCv: oneDayeCv,
      tenDayAst: tenDayAst,
      tenDayeCv: tenDayeCv,
      ast: ast,
      productId: productId
    }
  }

  const upColor = "#ec0000" /* 样本容量上升的颜色 */
  const upBorderColor = "#8A0000"
  const downColor = "#00da3c" /* 样本容量下降的颜色 */
  const downBorderColor = "#008F28"

  let myChart = null

  onMounted(() => {
    myChart = echarts.getInstanceByDom(document.getElementById("chart"))

    /**
     * echarts 图表宽度自适应
     */
    const resizeObserver = new ResizeObserver((entries, b) => {
      if(myChart){
        myChart.resize()
      }
    })
    resizeObserver.observe(document.getElementById("chart"))

    // 有的话就获取已有echarts实例的DOM节点
    // 如果不存在，就进行初始化
    if (myChart == null) {
      myChart = echarts.init(document.getElementById("chart"))
    }

    // 指定图表的配置项和数据

    var option = {
      animation: true,
      // 图表标题配置
      title: {
        text: ''
      },
      // 图例
      legend: {
        right: '50',
        data: ['1D_AST', '均值', '众数', 'ST目标', '10D_AST', '样本量', '1_D离散', '10_D离散']
      },
      // 提示框组件
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        textStyle: {
          color: '#000',
          fontSize: 12
        },
        // position: function (pos, params, el, elRect, size) {
        //   const obj = {
        //     top: 100
        //   }
        //   obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
        //   return obj
        // },
        formatter: function(params) {
          let str = ''
          params.forEach((item, idx, arr) => {
            if(item.seriesType === 'candlestick'){
              str += `${item.axisValue}<br/>${item.marker}${item.seriesName}`
            } else {
              if(Array.isArray(item.data)){
                str += `${item.axisValue}<br/>${item.marker}${item.seriesName}<span style="float: right;">${item.data[1]}</span>`
              } else {
                str += `${item.marker}${item.seriesName}<span style="float: right; margin-left: 50px;">${item.data}</span>`
              }
            }
            if(Array.isArray(item.data) && item.seriesType !== 'bar'){
              str += `
                <br/> <span style="display:inline-block;margin-left:6px;margin-right:4px;border-radius:6px;width:6px;height:6px;background-color:${item.color};"></span> Q1 <span style="float: right;">${item.color === '#ec0000' ? item.data[1].toFixed(2) : item.data[2].toFixed(2)}</span>
  
                <br/> <span style="display:inline-block;margin-left:6px;margin-right:4px;border-radius:6px;width:6px;height:6px;background-color:${item.color};"></span> 中位 <span style="float: right;">${item.color === '#ec0000' ? item.data[2].toFixed(2) : item.data[1].toFixed(2)}</span>
  
                <br/> <span style="display:inline-block;margin-left:6px;margin-right:4px;border-radius:6px;width:6px;height:6px;background-color:${item.color};"></span> 最小 <span style="float: right;">${item.data[3]}</span>
  
                <br/> <span style="display:inline-block;margin-left:6px;margin-right:4px;border-radius:6px;width:6px;height:6px;background-color:${item.color};"></span> Q3 <span style="float: right;">${item.data[4]}</span>
                
                
                `
            }
            str += idx === params.length - 1 ? '': '<br/>'
          })
          return str
        }
      },
      axisPointer: {
        link: [
          {
            xAxisIndex: 'all'
          }
        ],
        label: { // 文本标签的背景颜色
          backgroundColor: '#777'
        }
      },
      toolbox: {
        feature: {
          saveAsImage: {}, // 保存图片
          // dataZoom: {
          //   yAxisIndex: false
          // },
          brush: {
            type: ['']
          }
        }
      },
      brush: {
        xAxisIndex: 'all',
        brushLink: 'all',
        outOfBrush: {
          colorAlpha: 0.1
        }
      },
      visualMap: {
        show: false,
        seriesIndex: 5,
        dimension: 2,
        pieces: [ // 分段型视觉映射组件
          {
            value: 1,
            color: '#bfbfbf'
          },
          {
            value: -1,
            color: upColor
          }
        ]
      },
      grid: [
        {
          left: '5%',
          right: '20',
          height: '45%',
          top: '8%'
        },
        {
          left: '5%',
          right: '20',
          top: '65%',
          height: '10%'
        },
        {
          left: '5%',
          right: '20',
          top: '80%',
          height: '10%'
        }
      ],
      xAxis: [],
      yAxis: [],
      dataZoom: [],
      series: []
    }
    myChart.setOption(option)
  })

  const getDetails = () => {
    open.value = true
  }

  const getChartData = () => {
    getEqpChartData({
      dataTime: moment().subtract(90, 'days').format('YYYY-MM-DD'),
      dataTimeEnd: moment().format('YYYY-MM-DD'),
      machineId: queryParams.value.radio === 'EQP' ? queryParams.value.eqpType : queryParams.value.unitType,
      queryType: queryParams.value.radio
    }).then((res) => {
      const data = splitData(res.rows)
      const asyncOption = {
        title: {
          text: `${queryParams.value.eqpType} AST_1D K线趋势图`,
          textStyle: {
            fontSize:'16px',
            fontWeight: 600
          }
        },
        xAxis: [
          {
            type: 'category',
            data: data.categoryData,
            boundaryGap: true,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
              z: 100
            }
          },
          {
            type: 'category',
            gridIndex: 1,
            data: data.categoryData,
            boundaryGap: true,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            min: 'dataMin',
            max: 'dataMax'
          },
          {
            type: 'category',
            gridIndex: 2,
            data: data.categoryData,
            boundaryGap: true,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            min: 'dataMin',
            max: 'dataMax'
          }
        ],
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: true
            }
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            splitLine: { show: false }
            // axisLabel: { show: false },
            // axisLine: { show: false },
            // axisTick: { show: false },
          },
          {
            scale: true,
            gridIndex: 2,
            splitNumber: 2,
            splitLine: { show: false }
            // axisLabel: { show: false },
            // axisLine: { show: false },
            // axisTick: { show: false },
          }
        ],
        series: [
          {
            name: '1D_AST',
            type: 'candlestick',
            data: data.values,
            itemStyle: {
              color: upColor,
              color0: downColor,
              borderColor: undefined,
              borderColor0: undefined
            }
          },
          {
            name: '均值',
            type: 'line',
            data: data.average,
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
            // symbol: 'circle' // 拐点形状
          },
          {
            name: '众数',
            type: 'line',
            data: data.mode,
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'ST目标',
            type: 'line',
            data: data.ast,
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: '10D_AST',
            type: 'line',
            data: data.tenDayAst,
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: '样本量',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            itemStyle: {
              color: '#bfbfbf' /* legend 颜色 */
            },
            data: data.volumes
          },
          {
            name: '1_D离散',
            type: 'line',
            smooth: true, // 平滑折线
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data.oneDayeCv
          },
          {
            name: '10_D离散',
            type: 'line',
            smooth: true, // 平滑折线
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data.tenDayeCv
          },
          { /* 图中隐藏  tooltip显示 */
            name: '产品型号',
            data: data.productId,
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2
          }
        ],
        dataZoom: [
          /**
           * @param {string / number / Date} startValue
           * @param {string / number / Date} endValue
           */
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            startValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[14],
            endValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[0]
          },
          {
            //  show: true,
            xAxisIndex: [1, 2],
            type: 'inside',
            top: '85%',
            startValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[14],
            endValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[0]
          },
          {
            show: true,
            xAxisIndex: [1, 2],
            type: 'slider',
            bottom: '10',
            height: 25,
            startValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[14],
            endValue: JSON.parse(JSON.stringify(data.categoryData)).reverse()[0]
          }
        ]
      }

      myChart.setOption(asyncOption)
    })
  }

  // 导出
  const handleExport = () => {
    proxy.download('ASTManage/astEqp/listLineChartExport', {
      dataTime: moment().subtract(90, 'days').format('YYYY-MM-DD'),
      dataTimeEnd: moment().format('YYYY-MM-DD'),
      machineId: queryParams.value.radio === 'EQP' ? queryParams.value.eqpType : queryParams.value.unitType, /* 共用字段 machineId， radio选值不同时 值来源不同 */
      queryType: queryParams.value.radio
    }, `AST_1D折线图${new Date().getTime()}.xlsx`)
  }

  const radioChangeVal = () => {
    queryParams.value.factoryAreaId = null
    queryParams.value.productionTypeId = null
    queryParams.value.machineTypeId = null
    queryParams.value.eqpType = null
    queryParams.value.unitType = null
  }

  /**
   * 级联
   *
   * 制造类型
   */
  const areaChange = (target) => {
    queryParams.value.productionTypeId = null
    queryParams.value.machineTypeId = null
    listProductionTypeOptions.value = []
    if(!target.length) return
    getModelType({
      factoryAreaIdList: queryParams.value.factoryAreaId
    }).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  /**
   * 级联
   *
   * EQP类型
   */
  const productionTypeIdChange = (target) => {
    queryParams.value.machineTypeId = null
    listMachineTypeOptions.value = []
    if(!target.length) return
    getMachineTypeId({
      productionTypeIdList: queryParams.value.productionTypeId,
      isMainmachineType: 'N'
    }).then((res) => {
      res.rows.forEach(item => {
        listMachineTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const machineTypeIdChange = () => {
    listEqpTypeOptions.value = []
    queryParams.value.eqpType = null
    getEqpTypeId({
      machineType: queryParams.value.machineTypeId,
      isAnalysis: queryParams.value.radio === 'EQP' ? 'Y' : 'N'
    }).then((res) => {
      res.data.forEach(item => {
        listEqpTypeOptions.value.push({
          label: item.machineId,
          value: item.machineId
        })
      })
    })
  }

  const eqpTypeChange = (value) => {
    if(queryParams.value.radio === 'UNIT'){

      listUnitTypeOptions.value = []
      queryParams.value.unitType = null
      getUnitOptions({
        machineId: value
      }).then((res) => {
        res.rows.forEach((item) => {
          listUnitTypeOptions.value.push({
            label: item,
            value: item
          })
        })
      })
    }
  }

</script>

<style scoped lang="less">
.el-radio {
  margin-right: 5px;
}

// .charts {
//   overflow: scroll;
// }

:deep(.el-form-item){
  // el-form-item el-form-item--small asterisk-left
  margin-right: 10px !important;
}
</style>